package com.wangsd.web.shop.service;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.query.Sort;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.shop.entity.Coupon;
import com.wangsd.web.shop.entity.Trade;
import com.wangsd.web.shop.mapper.TradeMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class TradeService {
    @Resource
    private TradeMapper mapper;
    @Autowired
    CouponService couponService;

    private Query getQuery(Trade queryObj, String code) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getOutTradeNo())) {
            query.like("out_trade_no", queryObj.getOutTradeNo());
        }
        if (StringUtils.isNotBlank(queryObj.getTransactionId())) {
            query.like("transaction_id", queryObj.getTransactionId());
        }
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("parent_code", code);
        }
        if (StringUtils.isNotBlank(queryObj.getParentCode())) {
            query.likeRight("parent_code", queryObj.getParentCode());
        }
        if (StringUtils.isNotBlank(queryObj.getMerchantCode())) {
            query.likeRight("parent_code", queryObj.getMerchantCode());
        }
        if (StringUtils.isNotBlank(queryObj.getProductNo())) {
            query.eq("product_no", queryObj.getProductNo());
        }
        if (StringUtils.isNotBlank(queryObj.getMiniOpenid())) {
            query.eq("mini_openid", queryObj.getMiniOpenid());
        }
        if (queryObj.getStatus() != null) {
            query.eq("status", queryObj.getStatus());
        }
        if (queryObj.getSendStatus() != null) {
            query.eq("send_status", queryObj.getSendStatus());
        }
        if (StringUtils.isNotBlank(queryObj.getBeginTime())) {
            query.ge("created_time", queryObj.getBeginTime());
        }
        if (StringUtils.isNotBlank(queryObj.getEndTime())) {
            query.le("created_time", queryObj.getEndTime());
        }
        return query;
    }

    public List<Trade> selectPage(Trade queryObj, String loginCode) {
        Query query = this.getQuery(queryObj, loginCode);
        query.orderby("created_time", Sort.DESC);
        List<Trade> list = mapper.list(query);
        return list;
    }

    /**
     * 查询今天售卖数量
     * @return
     */
    public long selectOnedayQuota(String stockId) {
        Date date = new Date();
        String startTime = DateUtils.formatDate(date);
        String endTime = DateUtils.formatDate(date) + " 23:59:59";
        Query query = new Query();
        query.eq("product_no", stockId);
        query.ge("created_time", startTime);
        query.le("created_time", endTime);
        return mapper.getCount(query);
    }

    /**
     * 根据条件统计
     * @param queryObj
     * @param loginCode
     * @return
     */
    public Map selectStatistics(Trade queryObj, String loginCode) {
        Query query = this.getQuery(queryObj, loginCode);
        List<String> column = Arrays.asList("count( 1 ) AS orderCount,\n" +
                "\tSUM( price ) * 0.01 AS orderAmount,\n" +
                "\tSUM( CASE WHEN status = 1 THEN 1 ELSE 0 END ) AS payCount,\n" +
                "\tSUM( CASE WHEN status = 1 THEN price ELSE 0 END ) * 0.01 AS payAmount,\n" +
                "\tSUM( CASE WHEN status = 0 OR status = 2 THEN 1 ELSE 0 END ) AS unpayCount,\n" +
                "\tSUM( CASE WHEN status = 0 OR status = 2 THEN price ELSE 0 END ) * 0.01 AS unpayAmount");
        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        Map<String, Object> map = new HashMap<>();
        if (mapList != null && mapList.size() > 0) {
            map = mapList.get(0);
        }
        return map;
    }

    public void save(Trade trade) {
        if (trade.getId() != null) {
            mapper.updateIgnoreNull(trade);
        }else {
            mapper.saveIgnoreNull(trade);
        }

    }

    public Trade selectByOutTradeNo(String outTradeNo) {
        return mapper.getByQuery(new Query().eq("out_trade_no", outTradeNo));
    }

    public Trade selectByOutTradeNoDelete(String outTradeNo) {
        return mapper.selectByOutTradeNoDelete(outTradeNo);
    }

    public List<Trade> selectByMiniOpenid(String miniOpenid, Integer status) {
        Query query = new Query();
        query.eq("mini_openid", miniOpenid);
        query.eq("status", status);
        query.orderby("created_time", Sort.DESC);
        return mapper.list(query);
    }

    public void update(Trade trade) {
        mapper.updateIgnoreNull(trade);
    }

    /**
     * 定时删除未支付的订单
     */
    @Transactional
    public void deleteByStatus() {
        List<Trade> list = mapper.selectByQuery();
        for (Trade trade : list) {
            Coupon coupon = couponService.selectByStockId(trade.getProductNo());
//            coupon.setDistributedCoupons(coupon.getDistributedCoupons() - 1);
//            couponService.update(coupon);
            couponService.updateDistributedCouponsSub(coupon.getId());
            mapper.deleteById(trade.getId());
        }
    }

    public long selectByStockIdAndMiniOpenid(String stockId, String miniOpenid) {
        Query query = new Query();
        query.eq("product_no", stockId);
//        query.notEq("status", 0);
        query.eq("mini_openid", miniOpenid);
        return mapper.getCount(query);
    }

    public Trade selectById(Long tradeId) {
        return mapper.getById(tradeId);
    }
}
